package com.sandking.net;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @UserName : SandKing
 * @DataTime : 2012-9-18 上午10:03:11
 * @Description ：Please describe this document
 */
public class SK_Rquest {
	public static final String HTTP_POST = "POST";
	public static final String HTTP_GET = "GET";

	public static String httpRquest(String urlStr, String postData,
			String method, String charSet) throws Exception {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		String res = null;
		try {
			byte[] data = postData.getBytes(charSet);
			URL url = new URL(urlStr);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setRequestMethod(method);
			httpConn.setRequestProperty("ContentType",
					"application/x-www-form-urlencoded");
			httpConn.setRequestProperty("Content-Length",
					String.valueOf(data.length));
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			// System.setProperty("sun.net.client.defaultConnectTimeout",
			// "30000");//jdk1.4换成这个,连接超时
			// System.setProperty("sun.net.client.defaultReadTimeout", "30000");
			// //jdk1.4换成这个,读操作超时
			httpConn.setConnectTimeout(30000);// jdk 1.5换成这个,连接超时
			httpConn.setReadTimeout(30000);// jdk 1.5换成这个,读操作超时
			httpConn.connect();
			OutputStream os = httpConn.getOutputStream();
			os.write(data);
			// 获得响应状态
			int responseCode = httpConn.getResponseCode();
			if (HttpURLConnection.HTTP_OK == responseCode) {
				byte[] buffer = new byte[1024];
				int len = -1;
				InputStream is = httpConn.getInputStream();
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				while ((len = is.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				res = bos.toString(charSet);
				is.close();
			} else {
				System.err.println(urlStr + " Response Code:" + responseCode);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			System.err.println(urlStr);
		} finally {
			if (null != writer) {
				writer.close();
			}
			if (null != httpConn) {
				httpConn.disconnect();
			}
		}
		return res;
	}
}
